//save,get
const express=require('express');
const router=express.Router();
const passport=require("passport");
const isExist=require('../../config/publicFun').isExist;
const Read=require('../../models/Read');


//$route  Post api/reads/doRead
//@desc   return state
//@access private
router.post("/doRead",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let option={
        user:req.user.id,
        post:req.body.post,
    };
    isExist(option,Read,doc=>{
        //如果不存在这个用户对这条博客的阅读记录就存一条
        if(doc.length==0){
            let read=new Read(option);
            read.save((err)=>{
                if(err){
                    res.json({"ok":1});
                }
                else{
                    res.json({"ok":0});
                }
            })
        }
        else{
            //如果存在这个用户对这条博客的阅读记录就不用操作
            res.json({"ok":2});
        }
    })
})

//$route  Post api/reads/getReads
//@desc   return postId
//@access private
//管理员权限用户点过赞的post
router.post('/getReads',passport.authenticate("jwt",{session:false}),(req,res)=>{
    if(req.user.identity=='admin'){
        Read.find({'user':req.user.id},{'_id':0,'post':1})
        .then((docs)=>{
            res.json({'ok':0,'data':docs});
        })
    }
})


module.exports=router;